//
//  HomePage_selectdata_Controller.m
//  Food
//
//  Created by dllo on 15/7/27.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "HomePage_selectdata_Controller.h"
#import "BaseHeader.h"
#import "Boutique_class_details_cell.h"
#import "selectData.h"
#import "AFNetworkHandler.h"
#import "select_Collection_Cell.h"
#import "HomePage_display_Controller.h"
#import "IngredientsFoodController.h"
#import "MJRefresh.h"
#import "select_View.h"
static int i = 1;
@interface HomePage_selectdata_Controller () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArry;
@property (nonatomic, retain) UITextField *textFile;
@property (nonatomic, retain) NSMutableArray *selectArry;
@property (nonatomic, retain) UILabel *lable1;
@end

@implementation HomePage_selectdata_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view

    
    self.title = @"搜索";
    self.view.backgroundColor = [UIColor redColor];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    [self createCollectionView];
}

- (void) viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
}

- (void) createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((ScreenWidth - 40) / 2.0, 120.0 / 375.0 *ScreenWidth);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumLineSpacing = 5;
    layout.headerReferenceSize = CGSizeMake(200 / 375.0 * ScreenWidth, 30);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 - 49) collectionViewLayout:layout];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backGround.jpg"]];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[select_Collection_Cell class] forCellWithReuseIdentifier:@"cell"];
    
    
    [self.collectionView registerClass:[select_View class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    select_Collection_Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    selectData *model = self.dataArry[indexPath.item];
    if (![model.type isEqualToString:@"4"]) {
        [cell setModel:model];
    }
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArry.count;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        select_View *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.tag = 1001;
        self.str = header.textFile.text;
        
        [header.button addTarget:self action:@selector(fun) forControlEvents:UIControlEventTouchUpInside];
        return header;
    }
    return nil;
}

- (void) fun
{
    [self addFooter];
    self.dataArry = [NSMutableArray array];
    i = 1;
    select_View *header = (select_View *) [self.view viewWithTag:1001];
    self.str = header.textFile.text;
    if (![self.str isEqualToString:@""]) {
        NSString *pathURL = [NSString stringWithFormat:@"http://121.41.88.194:80/HandheldKitchen/api/home/tblAssort!getDataList.do?name=%@&page=%d&pageRecord=10&is_traditional=0", self.str, i];
        //self.dataArry = [NSMutableArray array];
        [AFNetworkHandler getWithAFNByURL:pathURL completion:^(id result) {
            NSArray *tempArry = result[@"data"];
             NSArray *temparry = [selectData arrayWithModelByArray:tempArry];
            for (selectData *model in temparry) {
                if (![model.type isEqualToString:@"0"]) {
                    [self.dataArry addObject:model];
                }
            }
            if (self.dataArry.count == 0) {
                self.lable1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
                self.lable1.text = @"暂无数据";
                self.lable1.center = CGPointMake(self.view.center.x, ScreenHeight / 3.0);
                [self.view addSubview:self.lable1];
            } else
            {
                self.lable1.text = @"";
            }
            [self.collectionView reloadData];
        }];
    }
    else
    {
        UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入内容" delegate:self cancelButtonTitle:nil  otherButtonTitles:@"确定", nil];
        [alterView show];
        [alterView release];
    }
    
}

- (void) addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    //[self.collectionView addFooterWithTarget:self action:@selector(footerAction)];
    [self.collectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        i++;
        [self getdata:i];
        // 模拟延迟加载数据，因此2秒后才调用）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //[vc.collectionView reloadData];
            // 结束刷新
            [vc.collectionView footerEndRefreshing];
        });
    }];
}


- (void) getdata:(int)i
{
    UIActivityIndicatorView *activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
    activityIndicator.frame = CGRectMake(0, 0, 100, 100);
    activityIndicator.color = [UIColor grayColor];
    activityIndicator.center = CGPointMake(ScreenWidth / 2.0, ScreenHeight / 2.0 - 50);
    [self.view addSubview:activityIndicator];
    [activityIndicator startAnimating];
    
    NSString *pathURL = [NSString stringWithFormat:@"http://121.41.88.194:80/HandheldKitchen/api/home/tblAssort!getDataList.do?name=%@&page=%d&pageRecord=10&is_traditional=0", self.str, i];
    [AFNetworkHandler getWithAFNByURL:pathURL completion:^(id result) {
        NSArray *tempArry = result[@"data"];
         NSMutableArray *temparry = [selectData arrayWithModelByArray:tempArry];
        if (temparry.count == 0) {
            self.collectionView.footerRefreshingText = @"数据加载完毕";
        }
        for (selectData *model in temparry) {
            [self.dataArry addObject:model];
        }
        [self.collectionView reloadData];
        [activityIndicator stopAnimating];
        [self.collectionView footerEndRefreshing ];
    }];
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    selectData *model = self.dataArry[indexPath.item];
    if ([model.type isEqualToString:@"1"]) {
        HomePage_display_Controller *display = [[HomePage_display_Controller alloc] init];
        display.classid = model.classid;
        display.classTitle = model.name;
        display.MVBackGroundimage = model.imagePath;
        [self.navigationController pushViewController:display animated:YES];
    }
    if ([model.type isEqualToString:@"2"]) {
        IngredientsFoodController *ingredients = [[IngredientsFoodController alloc] init];
        ingredients.title = model.name;
        ingredients.getID = model.classid;
        [self.navigationController pushViewController:ingredients animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
